﻿using PagedList;
using PagedList.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GiaoTrinhEPU.Repositories.Repositories;
using GiaoTrinhEPU.Repositories.DataModels;
using GiaoTrinhEPU.Repositories;
using GiaoTrinhEPU.Repositories.Interfaces;
using GiaoTrinhEPU.Core.ActionResults;
using GiaoTrinhEPU.Core;
using WebMatrix.WebData;
using System.Web.Security;
using GiaoTrinhEPU.Filters;


namespace GiaoTrinhEPU.Areas.Manager.Controllers
{
    [InitializeSimpleMembership]
    [Authorize(Roles = "Administrator")] 
    public class UserController : Controller
    {
        /// <summary>
        /// Declare User Repository
        /// </summary>
        private UserRepository userRepository;

        /// <summary>
        ///  Declare Session
        /// </summary>
        public static string SessionUserSort = "SessionUserSort";
        public static string SessionUserSearch = "SessionUserSearch";
        public static string SessionUserSortOpt = "SessionUserSortOpt";



        // GET: /User/
        /// <summary>
        /// Constructor that allow to create a Comment controller
        /// </summary>
        public UserController()
            : base()
        {
            this.userRepository = new UserRepository();
            ViewBag.SelectedMenuId = 25;

        }

        public ActionResult Index(int page = 1, int size = 25, String search = "", String opt = "", String sort = "")
        {
            ViewBag.Title = "Tác Giả";
            // Stored Session
            Session[SessionUserSort] = sort.Trim().Length > 0 ? sort.ToLower() : Session[SessionUserSort];
            Session[SessionUserSortOpt] = opt.Trim().Length > 0 ? opt.ToLower() : Session[SessionUserSortOpt];
            var user = userRepository.ListUser().ToList();
       
            // Sort 
            ViewBag.SortNameOpt = "desc";
            if (Session[SessionUserSort] != null)
            {
                switch (Session[SessionUserSort].ToString())
                {
                    case "name":
                        //user = Session[SessionUserSortOpt].ToString().Equals("desc") ? user.OrderByDescending(s => s.Name).ToList() : user.OrderBy(s => s.Name).ToList();

                        Session[SessionUserSort] = "name";
                        ViewBag.SortNameOpt = Sort.SetSortOrderOption(Session[SessionUserSortOpt].ToString());
                        break;

                    default:
                        break;
                }
            }
            return View(user.ToPagedList(page,size));
           
        }
        /// <summary>
        /// Get
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
        /// <summary>
        /// create action with param
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(UserModel model)
        {
            ViewBag.EnabledMenu = false;

            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password, propertyValues: new { Email = model.Email ,Mobile=model.Mobile,Address=model.Address,Name=model.FullName});

                    Roles.AddUserToRole(model.UserName, model.Role);
                   
                    return RedirectToAction("Index").WithSuccessMessage("Đã tạo thành công nhân viên mới");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
           
        }

        [HttpGet]
        public ActionResult Edit(int UserId=0)
        {
            var user = userRepository.GetUserbyUserId(UserId);
            var userModel = new UserModel(user);
            return View(userModel);
        }

        [HttpPost]
        public ActionResult Edit(UserModel model)
        { 
            if(ModelState.IsValid)
            {
                var u = new UserProfile();
                u.Mobile = model.Mobile;
                u.Email = model.Email;
                u.Address = model.Address;
                u.Name = model.FullName;

                this.userRepository.UpdateUser(u);
                return RedirectToAction("Index").WithSuccessMessage("Đã sửa thành công người dùng");
      
            }
            return View(model);
        }


        [HttpPost]
        public ActionResult Delete(string userName, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
                if (Roles.GetRolesForUser(userName).Count() > 0)
                {
                    Roles.RemoveUserFromRoles(userName, Roles.GetRolesForUser(userName));
                }
                ((SimpleMembershipProvider)Membership.Provider).DeleteAccount(userName); // deletes record from webpages_Membership table
                ((SimpleMembershipProvider)Membership.Provider).DeleteUser(userName, true); // deletes record from UserProfile table

                return RedirectToAction("Index");
            }
            catch
            {
                return View(userName);
            }
        }
        /// <summary>
        /// Clear
        /// </summary>
        /// <returns></returns>
        public ActionResult Clear()
        {
            // Clear sessions
            Session[SessionUserSearch] = null;
            Session[SessionUserSort] = null;
            Session[SessionUserSortOpt] = null;

            return RedirectToAction("Index");
        }
       

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Tên đăng nhập đã tồn tại vui lòng chọn tên đăng nhập khác.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "Một tài khoản khác đã sử dụng email này.Vui lòng chọn email khác.";

                case MembershipCreateStatus.InvalidPassword:
                    return "Mật khẩu không chính xác.Vui lòng kiểm tra lại";

                case MembershipCreateStatus.InvalidEmail:
                    return "Email không chính xác.Vui lòng kiểm tra lại";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "Tên đăng nhập không chính xác.Vui lòng kiểm tra lại";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
    }
}
